using System;
using System.Reflection;
using System.Xml.Linq;
using Engine;

namespace RuthlessConquest {
    public class ServerConfig {
        public Server Server;

        public string LastLoadedConfig = string.Empty;

        public DateTime? LastAssemblyTime;

        public double NextUpdateTime;

        public string ServerName = "LocalServer";

        public int ServerPriority = 100;

        public bool ShutdownSequence;

        public ServerConfig(Server server) {
            Server = server;
            if (Server.IsDedicatedServer) {
                LoadConfigFile();
            }
        }

        public void Run() {
            if (!Server.IsDisposing
                && ShutdownSequence
                && Server.Games.Count == 0) {
                Log.Information("No games and ShutdownSequence started, server shutting down.");
                Server.Dispose();
            }
            if (!(Time.RealTime >= NextUpdateTime)) {
                return;
            }
            NextUpdateTime = Time.RealTime + 5.0;
            if (!Server.IsDedicatedServer) {
                return;
            }
            LoadConfigFile();
            DateTime fileLastWriteTime = Storage.GetFileLastWriteTime("system:" + Assembly.GetEntryAssembly().Location);
            if (LastAssemblyTime.HasValue) {
                DateTime value = fileLastWriteTime;
                DateTime? lastAssemblyTime = LastAssemblyTime;
                if (value != lastAssemblyTime) {
                    ShutdownSequence = true;
                }
            }
            else {
                LastAssemblyTime = fileLastWriteTime;
            }
        }

        public void LoadConfigFile() {
            string text = "app:ServerConfig.xml";
            try {
                string text2 = Storage.ReadAllText(text);
                if (text2 != LastLoadedConfig) {
                    LastLoadedConfig = text2;
                    XElement xElement = XElement.Parse(text2);
                    ServerName = xElement.Attribute("ServerName").Value;
                    ServerPriority = int.Parse(xElement.Attribute("ServerPriority").Value);
                    ShutdownSequence = bool.Parse(xElement.Attribute("ShutdownSequence").Value);
                    Log.Information("Loaded new config:\n" + text2);
                }
            }
            catch (Exception ex) {
                Log.Warning("Error loading config file " + text + ", reason: " + ex.Message);
            }
        }
    }
}